package com.op.studyingliteapp.task;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.op.studyingliteapp.bean.UserBean;
import com.op.studyingliteapp.common.Common;
import com.op.studyingliteapp.common.UserUrl;
import com.op.studyingliteapp.database.dao.UserDao;
import com.op.util.SharedPreferenceUtil;
import com.op.util.asynctask.HttpPostTask;
import com.op.util.asynctask.OnTaskProcessListener;

public class LoginTask extends HttpPostTask {

	private static final String TAG = LoginTask.class.getSimpleName();
	private LoginCallback callback;

	public interface LoginCallback {
		public void handleLoginResponse(String result);
	}

	public static LoginTask newTask(Context context, String userNumber, String userPassword) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("number", userNumber));
		params.add(new BasicNameValuePair("password", userPassword));
		LoginTask task = new LoginTask(context, UserUrl.LOGIN, params);
		return task;
	}

	public LoginTask(Context context, String path, List<NameValuePair> params) {
		super(context, path, params);
		this.setTaskListener(new OnTaskProcessListener() {

			@Override
			public void prepare() {

			}

			@Override
			public void completed(String result) {
				Log.i(TAG, "login result : " + result);
				callback.handleLoginResponse(result);
			}
		});
	}

	/**
	 * 保存获取的登录信息
	 * 
	 * @param jsonObject
	 */
	public static void saveData(Context context, JSONObject jsonObject) {
		try {
			if (jsonObject.getJSONObject(Common.JsonResult.RESULT_MAP) != null) {
				jsonObject = jsonObject.getJSONObject(Common.JsonResult.RESULT_MAP);
				if (jsonObject.getJSONObject(Common.JsonResult.LOGIN_USER) != null) {
					jsonObject = jsonObject.getJSONObject(Common.JsonResult.LOGIN_USER);
				}
			}
			// 1. 将JsonObject存入本地数据库
			UserBean userBean = new UserBean();
			userBean.fillAttributeByJson(jsonObject);
			UserDao userDao = new UserDao(context);
			userDao.insertOrUpdate(userBean);
			// 2. 将当前登录的用户信息保存到SharedPreference
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.USER_ID, userBean.getId());
			prefsMap.put(Common.Prefs.USER_Name, userBean.getName());
			prefsMap.put(Common.Prefs.USER_NUMBER, userBean.getNumber());
			prefsMap.put(Common.Prefs.USER_PWD, userBean.getPassword());
			prefsMap.put(Common.Prefs.USER_ImageUrl, userBean.getImageUrl());
			SharedPreferenceUtil.saveData(context, prefsMap);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void registerCallback(LoginCallback callback) {
		this.callback = callback;
	}

}